<?php
/*
 * Copyright (c) 2022.  Liuhongbin All rights reserved.
 * @domain http://dkyx.cc
 * @author liuhongbin <514660094@qq.com>
 */

namespace hiduoke\services\workWechat;

use app\common\model\platform\PlatformSetting;
use EasyWeChat\Factory;

trait WorkWechatCustomerService
{
    protected $customerConfig = null;

    /**
     * @var \EasyWeChat\Work\Application
     */
    protected $customerApp = null;

    /**
     * 获取客户联系配置
     * @return array
     */
    public function getCustomerConfig()
    {
        $customer = (new PlatformSetting())->getValueByKey("customer", $this->plaid);
        $config = [
            'corp_id' => $this->corp_id,
            'secret'  => $customer['secret'],
            'token'   => $customer['token'],
            'aes_key' => $customer['aes_key'],
            'log' => [
                'default' => 'error', // 默认使用的 channel，生产环境可以改为下面的 prod
                'channels' => [
                    'error' => [
                        'driver' => 'single',
                        'path' => '/tmp/easywechat/work_wechat_error.log',
                        'level' => 'error',
                    ],
                ],
            ],
        ];
        return $config;
    }

    /**
     * 获取客户联系Application
     * @param $config array 配置
     * @return \EasyWeChat\OpenWork\Work\Application|\EasyWeChat\Work\Application|null
     */
    public function getCustomerApp($config = [])
    {
        if ($this->auth_type == 'open') {
            // 服务商授权获取App
            $this->openApp = (new WorkWechatOpen())->getOpenApp();
            return $this->openApp->work($this->corp_id, $this->platform['config']['permanent_code']);
        } else {
            // 手动配置
            if ($this->customerApp) {
                return $this->customerApp;
            }
            if (!$config) {
                $this->customerConfig = $this->getCustomerConfig();
            } else {
                $this->customerConfig = $config;
            }
            $this->customerApp = Factory::work($this->customerConfig);
            return $this->customerApp;
        }
    }
}
